<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 展开行 type="expand" -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              :class="['bb',i1==0?'bt':'']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag @close="deleteRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <span class="el-icon-caret-right"></span>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2==0?'':'bt']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <span class="el-icon-caret-right"></span>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      @close="deleteRightById(scope.row,item3.id)"
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="80"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="280"></el-table-column>
        <el-table-column prop="roleDesc" label="角色表述" width="280"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            {{scope.row.id}}
            <el-button size="mini" type="primary" icon="el-icon-edit">修改</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              size="mini"
              type="warning"
              @click="showRightsDialog(scope.row)"
              icon="el-icon-setting"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 权限对话框 -->
      <el-dialog title="权限分配" :visible.sync="rightsDialogVisible"
       width="50%" @close="DialogClosed">
        <el-tree
          :data="rightsList"
          :props="TreeProp"
          show-checkbox
          default-expend-all
          node-key="id"
          :default-checked-keys="keys"
          ref="TreeRef"
        ></el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="rightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 角色列表数组
      rolesList: [],
      //   控制权限对话框的布尔值
      rightsDialogVisible: false,
      // 权限列表的数据
      rightsList: [],
      // 树形结构配置项
      TreeProp: {
        // 标准属性是以下哪个节点
        children: "children",
        // 用户看到的文字
        label: "authName",
      },
      // 默认选中的三级节点绑定的数组
      keys: [],
      id: '',
    };
  },
  methods: {
    //   获取角色列表的方法
    // 获取的数据保存在data中
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.rolesList = res.data;
    },
    //   删除权限
    async deleteRightById(role, rightId) {
      // console.log(roleId,rightId);
      const result = await this.$confirm(
        "此操作永久删除该权限，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          canceButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result != "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除指定权限失败");
      }
      this.$message.success("删除指定权限成功");
      role.children = res.data;
    },

    async showRightsDialog(role) {
      this.rightsDialogVisible = true;
      // 请求到数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status != 200) {
        return this.$message.error("获取权限失败");
      }
      this.rightsList = res.data;
      // 调用函数
      this.getDefaultKeys(role, this.keys);
      console.log(role.id);
      this.id = role.id;
    },
    // 获取数据
    getDefaultKeys(ele, arr) {
      if (!ele.children) {
        // 是三级节点 将对应的id拿到
        return arr.push(ele.id);
      }
      // 不是三级节点 继续调用自己
      ele.children.forEach((item) => {
        return this.getDefaultKeys(item, arr);
      });
    },
    DialogClosed() {
      // 当对话框关闭之后将数组情况，保证下次点开对话框追加的数组是一个空数组
      this.keys = [];
    },
    // 完成权限分配
    async setRights() {
      const str = this.$refs.TreeRef.getCheckedKeys()
        .concat(this.$refs.TreeRef.getHalfCheckedKeys())
        .join(",");
      const { data: res } = await this.$http.post(`roles/${this.id}/rights`, {
        rids: str
      });
      if (res.meta.status != 200) {
        return this.$message.error("分配权限失败");
      }
      this.$message.success("分配权限成功");
      // 关闭对话框
      this.rightsDialogVisible = false;
      // 重新获取数据
      this.getRolesList();
    },
  },
  created() {
    //   调用获取角色列表
    this.getRolesList();
  },
};
</script>

<style lang="less" scope>
.el-tag {
  margin: 10px;
}
.bt {
  border-top: 1px solid #ccc;
}
.bb {
  border-bottom: 1px solid #ccc;
}
.el-row {
  display: flex;
  align-items: center;
}
</style>